<template>
  <aside 
    :class="[
      'sidebar',
      'fixed inset-y-0 left-0 z-50 flex flex-col border-r border-gray-200 transition-all duration-300',
      collapsed ? 'w-16' : 'w-64',
      'lg:relative lg:translate-x-0',
      isMobile && !collapsed ? 'translate-x-0' : isMobile ? '-translate-x-full' : ''
    ]"
    style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
  >
    <!-- 侧边栏头部 -->
    <div class="flex items-center justify-between h-16 px-4 border-b border-gray-200">
      <div v-if="!collapsed" class="flex items-center space-x-3">
        <img 
          v-if="logo" 
          :src="logo" 
          :alt="title"
          class="h-8 w-8"
        >
        <div v-else class="h-8 w-8 bg-blue-500 rounded-[0.6rem] flex items-center justify-center">
          <i class="icon-[heroicons--academic-cap] w-5 h-5 text-white"></i>
        </div>
        
        <h2 class="text-lg font-semibold text-gray-900">{{ title }}</h2>
      </div>
      
      <button
        v-if="!isMobile"
        @click="toggleCollapse"
        class="p-1.5 rounded-[0.6rem] text-gray-500 hover:bg-gray-100 hover:text-gray-700 transition-all duration-200 active:scale-[0.985]"
        style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
      >
        <i :class="collapsed ? 'icon-[heroicons--chevron-right]' : 'icon-[heroicons--chevron-left]'" class="w-4 h-4"></i>
      </button>
    </div>

    <!-- 导航菜单 -->
    <nav class="flex-1 overflow-y-auto py-4">
      <ul class="space-y-1 px-3">
        <li v-for="item in menuItems" :key="item.key">
          <!-- 单级菜单 -->
          <router-link
            v-if="!item.children"
            :to="item.to"
            :class="[
              'nav-link',
              isActive(item.to) ? 'nav-link-active' : 'nav-link-inactive'
            ]"
            @click="handleMenuClick(item)"
          >
            <i :class="item.icon" class="w-5 h-5 flex-shrink-0"></i>
            <span v-if="!collapsed" class="ml-3 truncate">{{ item.label }}</span>
            
            <!-- 徽章 -->
            <span 
              v-if="item.badge && !collapsed" 
              class="ml-auto inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800"
            >
              {{ item.badge }}
            </span>
          </router-link>
          
          <!-- 多级菜单 -->
          <div v-else>
            <button
              :class="[
                'nav-link w-full justify-between',
                hasActiveChild(item) ? 'nav-link-active' : 'nav-link-inactive'
              ]"
              @click="toggleSubmenu(item.key)"
            >
              <div class="flex items-center">
                <i :class="item.icon" class="w-5 h-5 flex-shrink-0"></i>
                <span v-if="!collapsed" class="ml-3 truncate">{{ item.label }}</span>
              </div>
              
              <i 
                v-if="!collapsed"
                :class="[
                  'w-4 h-4 transition-transform duration-200',
                  expandedMenus.includes(item.key) 
                    ? 'icon-[heroicons--chevron-up]' 
                    : 'icon-[heroicons--chevron-down]'
                ]"
              ></i>
            </button>
            
            <!-- 子菜单 -->
            <ul 
              v-if="!collapsed && expandedMenus.includes(item.key)"
              class="mt-1 space-y-1 pl-8"
            >
              <li v-for="child in item.children" :key="child.key">
                <router-link
                  :to="child.to"
                  :class="[
                    'nav-link text-sm',
                    isActive(child.to) ? 'nav-link-active' : 'nav-link-inactive'
                  ]"
                  @click="handleMenuClick(child)"
                >
                  <i :class="child.icon" class="w-4 h-4 flex-shrink-0"></i>
                  <span class="ml-2 truncate">{{ child.label }}</span>
                  
                  <span 
                    v-if="child.badge" 
                    class="ml-auto inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800"
                  >
                    {{ child.badge }}
                  </span>
                </router-link>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </nav>

    <!-- 侧边栏底部 -->
    <div v-if="$slots.footer" class="border-t border-gray-200 p-4">
      <slot name="footer"></slot>
    </div>
    
    <!-- 默认底部信息 -->
    <div v-else-if="!collapsed" class="border-t border-gray-200 p-4">
      <div class="text-xs text-gray-500 text-center">
        <p>{{ title }}</p>
        <p class="mt-1">v1.0.0</p>
      </div>
    </div>
  </aside>
  
  <!-- 移动端遮罩 -->
  <div 
    v-if="isMobile && !collapsed"
    class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"
    @click="closeSidebar"
  ></div>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '../../stores/app'
import { useAuthStore } from '../../stores/auth'

// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: '管理系统'
  },
  logo: {
    type: String,
    default: ''
  },
  menuItems: {
    type: Array,
    default: () => []
  }
})

// 定义事件
const emit = defineEmits(['menu-click'])

// 使用stores和路由
const appStore = useAppStore()
const authStore = useAuthStore()
const route = useRoute()

// 响应式数据
const expandedMenus = ref([])

// 计算属性
const collapsed = computed(() => appStore.sidebarCollapsed)
const isMobile = computed(() => appStore.isMobile)

// 方法
const toggleCollapse = () => {
  appStore.toggleSidebar()
}

const closeSidebar = () => {
  if (isMobile.value) {
    appStore.setSidebarCollapsed(true)
  }
}

const isActive = (path) => {
  if (!path) return false
  return route.path === path || route.path.startsWith(path + '/')
}

const hasActiveChild = (item) => {
  if (!item.children) return false
  return item.children.some(child => isActive(child.to))
}

const toggleSubmenu = (key) => {
  const index = expandedMenus.value.indexOf(key)
  if (index > -1) {
    expandedMenus.value.splice(index, 1)
  } else {
    expandedMenus.value.push(key)
  }
}

const handleMenuClick = (item) => {
  // 在移动端点击菜单后关闭侧边栏
  if (isMobile.value) {
    appStore.setSidebarCollapsed(true)
  }
  
  emit('menu-click', item)
}

// 监听路由变化，自动展开包含当前路由的菜单
watch(
  () => route.path,
  (newPath) => {
    props.menuItems.forEach(item => {
      if (item.children) {
        const hasActive = item.children.some(child => isActive(child.to))
        if (hasActive && !expandedMenus.value.includes(item.key)) {
          expandedMenus.value.push(item.key)
        }
      }
    })
  },
  { immediate: true }
)

// 监听折叠状态，折叠时关闭所有子菜单
watch(collapsed, (newCollapsed) => {
  if (newCollapsed) {
    expandedMenus.value = []
  }
})
</script>

<style scoped>
.sidebar {
  /* 确保侧边栏在移动端正确显示 */
}

/* 滚动条样式 */
nav::-webkit-scrollbar {
  width: 4px;
}

nav::-webkit-scrollbar-track {
  background: transparent;
}

nav::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 2px;
}

nav::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}
</style>